// CodeMirror
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
    mode: "htmlmixed", //要使用的模式
    theme: "default", //主题
    lineNumbers: true, //行号
    styleActiveLine: true, //高亮当前行
    indentWithTabs: false, //使用tab键缩进
    tabSize: 4, //tab键缩进单位
    indentUnit: 4, //缩进单位
    smartIndent: true, //智能缩进
    autoCloseTags: true, //自动闭合标签
    autoCloseBrackets: true, //自动闭合括号
    autofocus: true, //自动获取焦点
});

// 添加自动触发逻辑
editor.on('inputRead', (cm, event) => {
    if (!cm.state.completionActive) {
        cm.showHint();
    }
});

// 代码预览
const updatePreview = _.debounce(() => {
    const html = editor.getValue();
    document.title = html.match(/<title>([\s\S]*?)<\/title>/i)?.[1]?.trim() || 'Editor';
    document.getElementById('preview').srcdoc = html;
}, 100);

editor.on('change', updatePreview);

// 菜单
const examples = {
    demo: {
        title: "示例",
        html: "custom/examples/demo.html"
    },
    base: {
        title: "模板",
        html: "custom/examples/base.html"
    },
    train: {
        title: "飞驰的火车",
        html: "custom/examples/train.html"
    },
    dog: {
        title: "机器狗",
        html: "custom/examples/dog.html"
    },
    print: {
        title: "3D打印",
        html: "custom/examples/print.html"
    },
    wind: {
        title: "风力发电",
        html: "custom/examples/wind.html"
    },
    face: {
        title: "笑脸图",
        html: "custom/examples/face.html"
    },
    facesvg: {
        title: "笑脸图SVG",
        html: "custom/examples/facesvg.html"
    }
};

const examplesMenu = document.getElementById('examplesMenu');
Object.entries(examples).forEach(([key, example]) => {
    const li = document.createElement('li');
    li.className = 'menu-item';
    li.textContent = example.title;
    li.dataset.exampleKey = key;
    examplesMenu.appendChild(li);
});

document.querySelectorAll('.nav-item').forEach(item => {
    item.addEventListener('mouseenter', () => {
        const menu = item.querySelector('.dropdown-menu');
        const rect = item.getBoundingClientRect();
        if (!menu) return;
        if (rect.right + 150 > window.innerWidth) {
            menu.style.left = 'auto';
            menu.style.right = '0';
        } else {
            menu.style.right = 'auto';
            menu.style.left = '0';
        }
    });
});

// 处理菜单项点击事件
function loadExample(example) {
    fetch(examples[example].html)
        .then(response => response.text())
        .then(data => {
            editor.setValue(data);
        })
        .catch(error => console.error('Error loading example:', error));
};

function generateFileName() {
    const content = editor.getValue();
    const titleMatch = content.match(/<title>(.*?)<\/title>/i);
    if (titleMatch && titleMatch[1]) {
        return `${titleMatch[1].trim().replace(/[\\/:*?"<>|]/g, '')}.html`;
    }
    return null;
};

examplesMenu.addEventListener('click', (event) => {
    const exampleKey = event.target.dataset.exampleKey;
    if (exampleKey && examples[exampleKey]) {
        fetch(examples[exampleKey].html)
            .then(response => response.text())
            .then(html => {
                editor.setValue(html);
            })
            .catch(error => console.error('Error loading example:', error));
    }
});

manualMenu.addEventListener('click', (event) => {
    const url = event.target.dataset.url;
    if (url) {
        window.open(url, '_blank');
    }
});

aiMenu.addEventListener('click', (event) => {
    const url = event.target.dataset.url;
    if (url) {
        window.open(url, '_blank');
    }
});

// 新建文件功能
document.querySelector('#newFile').addEventListener('click', () => {
    if (editor.getValue() && !confirm('当前内容未保存，确定要新建吗？')) return;
    editor.setValue('');
    localStorage.removeItem('autoSave');
});

// 打开文件功能
document.querySelector('#openFile').addEventListener('click', () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.html,.htm,.txt';

    input.onchange = e => {
        const file = e.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = () => {
            editor.setValue(reader.result);
            showToast(`已打开: ${file.name}`);
            updatePreview();
        };
         reader.readAsText(file);
    };

    input.click();
});

// 文件拖放支持
document.addEventListener('dragover', e => e.preventDefault());
document.addEventListener('drop', e => {
    e.preventDefault();
    const file = e.dataTransfer.files[0];
    if (file && file.type.match(/text\/html|text\/plain/)) {
        const reader = new FileReader();
        reader.onload = () => editor.setValue(reader.result);
        reader.readAsText(file);
    }
});

// 保存文件功能
document.querySelector('#saveFile').addEventListener('click', () => {
    const content = editor.getValue();
    const blob = new Blob([content], { type: 'text/html' });
    const url = URL.createObjectURL(blob);

    // 自动生成文件名
    const fileName = generateFileName() || `document-${Date.now()}.html`;

    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    a.style.display = 'none';

    document.body.appendChild(a);
    a.click();

    setTimeout(() => {
        URL.revokeObjectURL(url);
        document.body.removeChild(a);
    }, 100);
});

// 每10秒自动保存
setInterval(() => {
    localStorage.setItem('autoSave', editor.getValue());
}, 1000 * 60);

// 启动时恢复
window.addEventListener('DOMContentLoaded', () => {
    const saved = localStorage.getItem('autoSave');
    editor.setValue(saved);
});